import 'dart:async';
import 'dart:core';
import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import '../../model/Types.dart';
import '../loginregister/Login.dart';
import '../../utils/Tool/MyTools.dart';
import '../../widgets/MyLocalImage.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';

import '../../base/MyScaffold.dart';
import '../../config/Constant.dart';
import '../../model/Bus.dart';
import '../../model/ConvertTypes.dart';
import '../../res.dart';
import '../../utils/EventBus/EventBus.dart';
import '../../utils/Toast/MyTosat.dart';
import '../../utils/color/ColorUtils.dart';
import '../../utils/userbloc/user_bloc.dart';
import '../../widgets/TextView.dart';
import '../convert/ToPDF.dart';
import '../process/Processing.dart';
import '../subscribe/Subscribe.dart';

class Tool extends StatefulWidget {
  const Tool({Key? key}) : super(key: key);

  @override
  State<Tool> createState() => _ToolState();
}

class _ToolState extends State<Tool> {
  List<ConvertType> convertlist = [];
  late File file;
  StreamSubscription? subscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    List<Types> items1 = [];
    items1.add(Types("import_a_pdf".tr, Res.tool_icon_import, 1, []));
    convertlist.add(ConvertType("pdf_tools".tr, items1));
    List<Types> items2 = [];
    items2.add(Types("convert_to_pdf".tr, Res.tool_icon_topdf, 2, ["PDF"]));
    items2.add(Types("pdf_to_word".tr, Res.tool_icon_toword, 3,
        ["DOC", "DOCX", "RTF", "DOT", "DOTX", "DOTM", "FlatOPC"]));
    items2.add(Types("pdf_to_image".tr, Res.tool_icon_toimg, 4,
        ["JPEG", "PNG", "BMP", "SVG", "TIFF", "EMF"]));
    items2.add(Types("pdf_to_web".tr, Res.tool_icon_toweb, 5,
        ["HTML", "MHTML", "HtmlFixed"]));
    items2.add(Types("pdf_to_pcl".tr, Res.tool_icon_topcl, 6, ["PCL"]));
    items2.add(Types("pdf_to_txt".tr, Res.tool_icon_totxt, 7, ["TXT"]));
    items2.add(Types(
        "pdf_to_openoffice".tr, Res.tool_icon_toopenoffice, 8, ["ODT", "OTT"]));
    items2.add(Types("pdf_to_xml".tr, Res.tool_icon_toxml, 9, ["XML"]));
    // items2
    //     .add(Type("PDF to Fixed Layout", Res.tool_icon_tofixedlayout, 10, ""));
    convertlist.add(ConvertType("format_conversion".tr, items2));

    subscription = EventBusUtil.addListener<Bus>((event) {
      if (event.label == Constant.USER_INFORMATION_UPDATE) {
        print("USER_INFORMATION_UPDATE====");
        var lang = SpUtil.getString(Constant.lanuage);
        var code = SpUtil.getString(Constant.code);
        if (!MyTools.stringIsEmpty(lang)) {
          var locale = Locale(lang!, code);
          Get.updateLocale(locale);
        }
        initState();
        setState(() {});
      }
    });
  }

  Future<void> _selectFile() async {
    final result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['pdf'], // 允许选择的文件扩展名
    );

    if (result != null) {
      file = File(result.files.single.path!);
      // 在这里处理文件，例如读取文件内容或显示文件信息
      print("1111$file");
      EventBusUtil.fireEvent(Bus(Constant.ADD_FILE_MSG, file));
      // setState(() {});
    } else {
      // 处理用户取消选择文件的情况
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    EventBusUtil.removeListener(subscription!);
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      navBarHide: true,
      body: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10),
        margin: const EdgeInsets.only(top: 16),
        child: Column(
          children: [
            Row(
              children: [
                TextView(
                  "tool".tr,
                  height: 30,
                  style: TextStyle(
                      color: rgba(48, 49, 51, 1),
                      fontSize: 20,
                      fontWeight: FontWeight.bold),
                ),
                const Spacer(),
                if (UserBlocTool.getUser()?.is_vip == "0" ||
                    !UserBlocTool.isLogin())
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 10),
                    child: MyLocalImage(
                      Res.nav_icon_getpro3x,
                      width: 52,
                      height: 24,
                      onclick: () {
                        Get.to(const Subscribe());
                      },
                    ),
                  ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  child: MyLocalImage(
                    Res.sys_icon_task,
                    width: 24,
                    height: 24,
                    onclick: () {
                      Get.to(const Processing());
                    },
                  ),
                ),
                MyLocalImage(
                  Res.sys_icon_sidebar,
                  width: 24,
                  height: 24,
                  onclick: () {
                    Scaffold.of(context).openDrawer();
                  },
                )
              ],
            ),
            Expanded(
              child: Container(
                margin: const EdgeInsets.only(top: 30),
                child: ListView.builder(
                  physics: const NeverScrollableScrollPhysics(),
                  itemBuilder: (c, p) {
                    var item = convertlist[p];
                    return Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        TextView(
                          item.title,
                          style: TextStyle(
                              color: rgba(48, 49, 51, 1),
                              fontSize: 16,
                              fontWeight: FontWeight.bold),
                          alignment: Alignment.centerLeft,
                        ),
                        Container(
                          margin: const EdgeInsets.only(top: 20, bottom: 20),
                          child: GridView.builder(
                              gridDelegate:
                                  const SliverGridDelegateWithFixedCrossAxisCount(
                                //设置列数
                                crossAxisCount: 4,
                                //设置横向间距
                                crossAxisSpacing: 6,
                                //设置主轴间距
                                mainAxisSpacing: 6,
                              ),
                              physics: const NeverScrollableScrollPhysics(),
                              //是否允许内容适配           非常非常非常非常重要
                              shrinkWrap: true,
                              scrollDirection: Axis.vertical,
                              itemCount: item.items.length,
                              itemBuilder: (context, index) {
                                return InkWell(
                                  onTap: () {
                                    // MyToast().show(context, item.items[index].name);
                                    if (item.items[index].label == 1) {
                                      _selectFile();
                                    } else {
                                      if (UserBlocTool.isLogin()) {
                                        Get.to(ConvertPDF(
                                          type: item.items[index],
                                        ));
                                      } else {
                                        MyToast().show("please_log".tr,
                                            icon_tips: false);
                                        Get.to(const Login());
                                      }
                                    }
                                  },
                                  child: Column(
                                    children: [
                                      Image(
                                        image:
                                            AssetImage(item.items[index].img),
                                        width: 40,
                                        height: 40,
                                      ),
                                      TextView(
                                        item.items[index].name,
                                        margin: const EdgeInsets.only(top: 10),
                                        style: TextStyle(
                                            color: rgba(48, 49, 51, 1),
                                            fontSize: 12),
                                        maxLines: 2,
                                        textAlign: TextAlign.center,
                                      )
                                    ],
                                  ),
                                );
                              }),
                        )
                      ],
                    );
                  },
                  itemCount: convertlist.length,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
//
